<!-- TemplateVariableInserter.vue -->
<template>
  <div class="variable-inserter">
    <!-- 触发按钮 -->
    <el-button
      type="primary"
      icon="el-icon-edit"
      @click="showInsertDialog"
      class="insert-trigger"
      v-if="!embedded"
    >
      插入模板变量
    </el-button>

    <!-- 主插入对话框 -->
    <el-dialog
      title="插入模板变量"
      :visible.sync="dialogVisible"
      width="90%"
      top="5vh"
      custom-class="variable-inserter-dialog"
      @opened="onDialogOpened"
      @closed="onDialogClosed"
    >
      <div class="inserter-container">
        <!-- 顶部操作栏 -->
        <div class="toolbar">
          <el-input
            v-model="searchText"
            placeholder="搜索参数名称或Code编码..."
            prefix-icon="el-icon-search"
            clearable
            style="width: 300px;"
            @input="onSearch"
          ></el-input>
          
          <div class="toolbar-actions">
            <el-button
              size="small"
              @click="showQuickInsert = !showQuickInsert"
            >
              {{ showQuickInsert ? '隐藏' : '显示' }}快捷插入
            </el-button>
            <el-button
              size="small"
              @click="exportVariables"
            >
              导出变量列表
            </el-button>
          </div>
        </div>

        <!-- 快捷插入区域 -->
        <div v-if="showQuickInsert" class="quick-insert-section">
          <el-divider content-position="left">常用变量</el-divider>
          <div class="quick-variables">
            <el-tag
              v-for="item in quickVariables"
              :key="item.code"
              type="info"
              class="quick-tag"
              @click="insertVariable(item.code)"
              closable
              @close="removeQuickVariable(item.code)"
            >
              {{ item.name }}
            </el-tag>
            <el-button
              size="mini"
              icon="el-icon-plus"
              @click="addToQuickVariables"
            >
              添加常用
            </el-button>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
          <!-- 参数列表 -->
          <div class="param-list-section">
            <div class="section-header">
              <h4>参数列表 ({{ filteredParams.length }})</h4>
              <el-button
                size="mini"
                @click="selectAll"
                :disabled="filteredParams.length === 0"
              >
                全选
              </el-button>
              <el-button
                size="mini"
                @click="clearSelection"
                :disabled="selectedParams.length === 0"
              >
                清空
              </el-button>
            </div>

            <div class="param-table-container">
              <el-table
                ref="paramTable"
                :data="filteredParams"
                height="400"
                @selection-change="onSelectionChange"
                @row-click="onRowClick"
                highlight-current-row
                :row-class-name="getRowClassName"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="paramName" label="参数名称" min-width="200" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span>{{ scope.row.paramName }}</span>
                    <el-tag
                      v-if="scope.row.required"
                      type="danger"
                      size="mini"
                      style="margin-left: 5px;"
                    >
                      必填
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="paramCode" label="Code编码" min-width="180" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <code>{{ scope.row.paramCode }}</code>
                  </template>
                </el-table-column>
                <el-table-column prop="templateVariable" label="模板变量" min-width="200">
                  <template slot-scope="scope">
                    <el-tag
                      type="success"
                      class="variable-tag"
                      @click="copyToClipboard(scope.row.templateVariable)"
                    >
                      {{ scope.row.templateVariable }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="insertVariable(scope.row.paramCode)"
                    >
                      插入
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      @click="previewVariable(scope.row)"
                    >
                      预览
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>

          <!-- 右侧操作面板 -->
          <div class="action-panel">
            <div class="panel-section">
              <h4>已选变量 ({{ selectedParams.length }})</h4>
              <div class="selected-list">
                <div
                  v-for="param in selectedParams"
                  :key="param.paramCode"
                  class="selected-item"
                >
                  <span class="param-name">{{ param.paramName }}</span>
                  <code class="param-code">{{ param.paramCode }}</code>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-close"
                    @click="removeSelected(param.paramCode)"
                  ></el-button>
                </div>
                <div v-if="selectedParams.length === 0" class="empty-selection">
                  暂无选中变量
                </div>
              </div>
            </div>

            <div class="panel-section">
              <h4>插入选项</h4>
              <el-radio-group v-model="insertMode">
                <el-radio label="single">单个插入</el-radio>
                <el-radio label="batch">批量插入</el-radio>
              </el-radio-group>
              
              <div v-if="insertMode === 'batch'" class="batch-options">
                <el-input
                  v-model="separator"
                  placeholder="分隔符"
                  style="margin-top: 10px;"
                >
                  <template slot="prepend">分隔符</template>
                </el-input>
                <el-checkbox v-model="includeBrackets" style="margin-top: 10px;">
                  包含 ${}
                </el-checkbox>
              </div>
            </div>

            <div class="panel-section">
              <h4>预览</h4>
              <div class="preview-area">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="previewText"
                  readonly
                  placeholder="选中变量后将显示预览"
                ></el-input>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="insertSelectedVariables"
          :disabled="selectedParams.length === 0"
        >
          {{ insertMode === 'single' ? '插入选中变量' : '批量插入变量' }}
        </el-button>
        <el-button
          type="success"
          @click="copySelectedVariables"
          :disabled="selectedParams.length === 0"
        >
          复制到剪贴板
        </el-button>
      </div>
    </el-dialog>

    <!-- 变量预览对话框 -->
    <el-dialog
      title="变量预览"
      :visible.sync="previewVisible"
      width="600px"
    >
      <div class="preview-dialog">
        <h4>{{ previewParam.paramName }}</h4>
        <p><strong>Code编码:</strong> <code>{{ previewParam.paramCode }}</code></p>
        <p><strong>模板变量:</strong> <el-tag type="success">{{ previewParam.templateVariable }}</el-tag></p>
        <p><strong>是否必填:</strong> 
          <el-tag :type="previewParam.required ? 'danger' : 'success'">
            {{ previewParam.required ? '是' : '否' }}
          </el-tag>
        </p>
        <div class="preview-actions">
          <el-button type="primary" @click="insertVariable(previewParam.paramCode)">
            插入此变量
          </el-button>
          <el-button @click="copyToClipboard(previewParam.templateVariable)">
            复制变量
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'TemplateVariableInserter',
  props: {
    projectConfig: {
      type: Object,
      required: true
    },
    // 是否嵌入模式（不显示触发按钮）
    embedded: {
      type: Boolean,
      default: false
    },
    // 当前选中的Excel单元格信息
    currentCell: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      previewVisible: false,
      searchText: '',
      showQuickInsert: true,
      insertMode: 'single',
      separator: ', ',
      includeBrackets: true,
      
      allParams: [],
      selectedParams: [],
      previewParam: {},
      previewText: '',
      
      quickVariables: [
        { name: '样品编号', code: 'sampleNo' },
        { name: '项目名称', code: 'projectName' },
        { name: '标准规范', code: 'standardCode' },
        { name: '检测时间', code: 'timestamp' }
      ]
    }
  },
  computed: {
    filteredParams() {
      if (!this.searchText) {
        return this.allParams
      }
      const search = this.searchText.toLowerCase()
      return this.allParams.filter(param =>
        param.paramName.toLowerCase().includes(search) ||
        param.paramCode.toLowerCase().includes(search) ||
        param.templateVariable.toLowerCase().includes(search)
      )
    }
  },
  watch: {
    selectedParams: {
      handler(newVal) {
        console.log('selectedParams:', newVal)
        this.updatePreviewText()
      },
      deep: true
    },
    insertMode() {
      this.updatePreviewText()
    },
    separator() {
      this.updatePreviewText()
    },
    includeBrackets() {
      this.updatePreviewText()
    }
  },
  methods: {
    showInsertDialog() {
      this.dialogVisible = true
    },

    onDialogOpened() {
      // 生成参数列表
      this.allParams = this.$paramParser.generateParamMapping(this.projectConfig)
      this.clearSelection()
    },

    onDialogClosed() {
      this.searchText = ''
      this.clearSelection()
    },

    onSearch() {
      // 搜索时清空选择，避免选择不可见项
      this.$nextTick(() => {
        this.clearSelection()
      })
    },

    onSelectionChange(selection) {
      this.selectedParams = selection
    },

    onRowClick(row) {
      // 点击行时切换选择状态
      this.$refs.paramTable.toggleRowSelection(row)
    },

    getRowClassName({ row }) {
      return row.required ? 'required-row' : ''
    },

    selectAll() {
      this.$refs.paramTable.clearSelection()
      this.$nextTick(() => {
        this.filteredParams.forEach(row => {
          this.$refs.paramTable.toggleRowSelection(row)
        })
      })
    },

    clearSelection() {
      this.$refs.paramTable.clearSelection()
    },

    removeSelected(paramCode) {
      const row = this.selectedParams.find(p => p.paramCode === paramCode)
      if (row) {
        this.$refs.paramTable.toggleRowSelection(row, false)
      }
    },

    insertVariable(paramCode) {
      const templateVar = `\${${paramCode}}`
      
      // 发送插入事件到父组件
      this.$emit('insert-variable', {
        variable: templateVar,
        code: paramCode,
        cell: this.currentCell
      })
      
      this.$message.success(`已插入变量: ${templateVar}`)
      
      // 如果是单个插入模式，关闭对话框
      if (this.insertMode === 'single') {
        this.dialogVisible = false
      }
    },

    insertSelectedVariables() {
      if (this.insertMode === 'single' && this.selectedParams.length > 0) {
        // 插入第一个选中的变量
        this.insertVariable(this.selectedParams[0].paramCode)
      } else {
        // 批量插入所有选中变量
        this.selectedParams.forEach(param => {
          this.insertVariable(param.paramCode)
        })
        this.$message.success(`已批量插入 ${this.selectedParams.length} 个变量`)
        this.dialogVisible = false
      }
    },

    copySelectedVariables() {
      const text = this.previewText
      this.copyToClipboard(text)
      this.$message.success('已复制到剪贴板')
    },

    copyToClipboard(text) {
      const textarea = document.createElement('textarea')
      textarea.value = text
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        this.$message.success('复制成功')
      } catch (err) {
        this.$message.error('复制失败')
      }
      document.body.removeChild(textarea)
    },

    previewVariable(param) {
      this.previewParam = param
      this.previewVisible = true
    },

    updatePreviewText() {
      if (this.selectedParams.length === 0) {
        this.previewText = ''
        return
      }

      if (this.insertMode === 'single') {
        const param = this.selectedParams[0]
        this.previewText = this.includeBrackets ? 
          param.templateVariable : param.paramCode
      } else {
        const variables = this.selectedParams.map(param => 
          this.includeBrackets ? param.templateVariable : param.paramCode
        )
        this.previewText = variables.join(this.separator)
      }
    },

    addToQuickVariables() {
      if (this.selectedParams.length > 0) {
        const param = this.selectedParams[0]
        const exists = this.quickVariables.find(q => q.code === param.paramCode)
        if (!exists) {
          this.quickVariables.push({
            name: param.paramName,
            code: param.paramCode
          })
          this.$message.success('已添加到常用变量')
        } else {
          this.$message.info('该变量已在常用列表中')
        }
      }
    },

    removeQuickVariable(code) {
      const index = this.quickVariables.findIndex(q => q.code === code)
      if (index > -1) {
        this.quickVariables.splice(index, 1)
      }
    },

    exportVariables() {
      const data = this.allParams.map(param => ({
        参数名称: param.paramName,
        Code编码: param.paramCode,
        是否必填: param.required ? '是' : '否',
        模板变量: param.templateVariable
      }))
      
      // 触发导出事件
      this.$emit('export-variables', data)
    }
  }
}
</script>

<style scoped>
.inserter-container {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
}

.main-content {
  display: flex;
  flex: 1;
  gap: 20px;
  min-height: 0;
}

.param-list-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
}

.param-table-container {
  flex: 1;
  min-height: 0;
}

.action-panel {
  width: 300px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.panel-section {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
}

.panel-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.selected-list {
  max-height: 200px;
  overflow-y: auto;
}

.selected-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px;
  border-bottom: 1px solid #f0f0f0;
}

.selected-item:last-child {
  border-bottom: none;
}

.param-name {
  font-size: 12px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.param-code {
  font-size: 11px;
  color: #666;
  margin: 0 5px;
}

.empty-selection {
  text-align: center;
  color: #999;
  font-size: 12px;
  padding: 20px;
}

.quick-insert-section {
  margin-bottom: 15px;
}

.quick-variables {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.quick-tag {
  cursor: pointer;
}

.quick-tag:hover {
  opacity: 0.8;
}

.variable-tag {
  cursor: pointer;
  user-select: none;
}

.variable-tag:hover {
  opacity: 0.8;
}

.preview-dialog h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.preview-dialog p {
  margin: 10px 0;
}

.preview-actions {
  margin-top: 20px;
  text-align: center;
}

.insert-trigger {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格行样式 */
:deep(.required-row) {
  background-color: #fff2f0;
}

:deep(.required-row:hover > td) {
  background-color: #ffeae6 !important;
}

:deep(.el-table .current-row) {
  background-color: #f0f9ff;
}

:deep(.variable-inserter-dialog .el-dialog__body) {
  padding: 20px;
}
</style>